import { Directive, Injectable, forwardRef } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { AdDestroyComponent } from './destroy.component'
export type OnTouchedType = () => any
export type OnChangeType = (value: any) => void
@Directive()
@Injectable()
export class AdControlValueAccessor extends AdDestroyComponent implements ControlValueAccessor {
  static NG_VALUE_ACCESSOR(component: any) {
    return [
      {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => component),
        multi: true,
      },
    ]
  }
  isDisabled: boolean = false
  value: any
  onChange: OnChangeType = () => {}
  onTouched: OnTouchedType = () => {}
  writeValue(value: any): void {
    if (this.value !== value) {
      this.value = value
    }
  }
  registerOnChange(fn: OnChangeType): void {
    this.onChange = fn
  }
  registerOnTouched(fn: OnTouchedType): void {
    this.onTouched = fn
  }
  setDisabledState(isDisabled: boolean): void {
    this.isDisabled = isDisabled
  }
}
